package com.handpay.zztong.hp.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.util.Log;

import com.handpay.zztong.hp.log.HPLog;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.URI;

import static android.graphics.BitmapFactory.decodeFile;

/**
 * 无损图片压缩辅助
 *
 * @author fplei
 */
public class BitmapZipUtils {

    /**
     * 计算压缩值
     *
     * @param options
     * @param reqWidth  期望宽度
     * @param reqHeight 期望高度
     * @return
     */
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        // inSampleSize这个值决定图片的压缩率，取接近2的值
        int inSampleSize = 1;
        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        Log.i("result", "压缩比率：" + inSampleSize);
        return inSampleSize;
    }

    /**
     * 压缩图片
     *
     * @param fileUri    图片地址uri'
     * @param req_width  期望宽度
     * @param req_height 期望高度
     * @param req_zoom   质量压缩值（0-100）
     * @return
     */
    public static byte[] getCatBitmap(URI fileUri, int req_width, int req_height, int req_zoom) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        String path = new File(fileUri).getAbsolutePath();
        Bitmap res_bitmap = decodeFile(path, options);
        options.inSampleSize = calculateInSampleSize(options, req_width, req_height);
        options.inJustDecodeBounds = false;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        res_bitmap.compress(Bitmap.CompressFormat.JPEG, req_zoom, baos);
        try {
            while (baos.toByteArray().length / 1024 > 200) {
                baos.reset();
                req_zoom -= 2;
                res_bitmap.compress(Bitmap.CompressFormat.JPEG, req_zoom, baos);
            }
        } catch (Exception e) {
            // 出现异常默认30
            res_bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);
        }
        return baos.toByteArray();
    }

    /**
     * 压缩图片
     *
     * @param filepath   图片地址
     * @param req_width  期望宽度
     * @param req_height 期望高度
     * @param reqSize    压缩图片大小
     * @return
     */
    public static byte[] getCatBitmap(String filepath, int req_width, int req_height, int reqSize) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        filepath = filepath.startsWith("file:///") || filepath.startsWith("content:") ? new File(URI.create(filepath)).getAbsolutePath() : filepath;
        HPLog.d(HPLog.SSX_TAG, "-----------" + filepath + "------------");
        options.inJustDecodeBounds = true;
        Bitmap res_bitmap = BitmapFactory.decodeFile(filepath, options);
        options.inSampleSize = calculateInSampleSize(options, req_width, req_height);
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;
        options.inPurgeable = true;
        options.inInputShareable = true;
        options.inJustDecodeBounds = false;
        HPLog.d(HPLog.SSX_TAG, "手机品牌：" + getPhoneBrand());
        if (Build.VERSION.SDK_INT <= android.os.Build.VERSION_CODES.KITKAT_WATCH || getPhoneBrand().equals("Sony") || getPhoneBrand().equals("MeiZu")) {
            /***
             * <p>Sony MeiZu手机用BitmapFactory.decodeFile(filepath, options)方式获取Bitmap retun null </p>
             * <p>所以检测当 return null　的时候用下面 decodeByteArray(bitmapBytes,0,bitmapBytes.length,options)</p>
             */
            if (res_bitmap == null) {
                File file = new File(filepath);
                FileInputStream fileInputStream = null;
                byte[] bitmapBytes = new byte[(int) file.length()];
                try {
                    fileInputStream = new FileInputStream(file);
                    fileInputStream.read(bitmapBytes);
                    fileInputStream.close();
                    res_bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length, options);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } else {
            res_bitmap = decodeFile(filepath, options);
        }
        //压缩图片
        int reqQuality = 100;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        res_bitmap.compress(Bitmap.CompressFormat.JPEG, reqQuality, baos);
        try {
            while (baos.toByteArray().length / 1024 > reqSize) {
                baos.reset();
                reqQuality -= 5;
                res_bitmap.compress(Bitmap.CompressFormat.JPEG, reqQuality, baos);
            }
        } catch (Exception e) {
            res_bitmap.compress(Bitmap.CompressFormat.JPEG, 5, baos);
        }
        return baos.toByteArray();
    }


    /**
     * bitmapbyte
     *
     * @param res_bitmap
     * @return
     */
    public static byte[] bitmap2byte(Bitmap res_bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        res_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        return baos.toByteArray();
    }

    /**
     * 获取手机品牌
     *
     * @return
     */
    public static String getPhoneBrand() {
        return android.os.Build.BRAND;
    }
}
